package list;

import java.util.HashMap;
import java.util.Iterator;

/**
 * description:
 * author:张腾
 * date:2021-04-02
 */

/**
 * 栈 后进先出 使用链表实现
 * @param <T>
 */
public class Stack<T> implements Iterable<T>{
    private Node head;
    private int N;

    private class Node{
        T item;
        Node next;

        public Node(T item, Node next){
            this.item = item;
            this.next = next;
        }
    }

    public Stack(){
        this.head = new Node(null,null);
        this.N = 0;
    }

    public boolean isEmpty(){
        return N==0;
    }

    public int size(){
        return N;
    }

    //把t元素压栈
    //新压进来的元素都放在首节点的后面，用来保证先进后出
    public void push(T t){
        //找到首节点后的第一个节点
        Node oldFirst = head.next;
        Node newNode = new Node(t,null);
        //首节点指向新节点，新节点指向原来的第一个节点
        head.next = newNode;
        newNode.next = oldFirst;

        N++;
    }

    //出栈
    public T pop(){
        Node oldFirst = head.next;
        if (oldFirst==null){
            return null;
        }
        head.next = oldFirst.next;

        N--;
        return oldFirst.item;
    }

    @Override
    public Iterator<T> iterator() {
        return new SIterator();
    }

    private class SIterator implements Iterator{
        private Node n;
        public SIterator(){
            this.n = head;
        }

        @Override
        public boolean hasNext() {
            return n.next!=null;
        }

        @Override
        public Object next() {
            n = n.next;
            return n.item;
        }

    }

}
